#include<iostream>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>

using namespace std;

class Tcp_Client{

  public:
    Tcp_Client(string server_ip,int server_port)
      :_server_ip(server_ip)
       ,_server_port(server_port)
       ,_sock(-1)
  {}

    void InitClient()
    {
      //创建套接字
      _sock = socket(AF_INET,SOCK_STREAM,0);
      if(_sock<0)
      {
        cerr<<"socket fail"<<endl;
        exit(2);
      }
    }

    ~Tcp_Client()
    {
      if(_sock>=0)
      {
        close(_sock);
      }
    }

    void Request()
    {
      string msg;
      char buf[1024];
      while(1)
      {
        cout<<"Please Enter#:";
        getline(cin,msg);
        write(_sock,msg.c_str(),msg.size());

        ssize_t size = read(_sock,buf,sizeof(buf)-1);
        if(size>0)
        {
          buf[size]='\0';
          cout<<"server echo# "<<buf<<endl;
        }
        else if(size==0)
        {
          cout<<"server close"<<endl;
          break;
        }
        else 
        {
          cerr<<"read fail"<<endl;
          break;
        }
      }
    }

    void Start()
    {
      struct sockaddr_in peer;
      memset(&peer,'\0',sizeof(peer));
      peer.sin_family = AF_INET;
      peer.sin_port  = htons(_server_port);
      peer.sin_addr.s_addr=inet_addr(_server_ip.c_str());

      if(connect(_sock,(struct sockaddr*)&peer,sizeof(peer))==0)
      {
        cout<<"connect success...."<<endl;
        Request();//发起请求
      }
      else 
      {
        cerr<<"connect fail"<<endl;
        exit(3);
      }

    }

  private:
   int _sock;
   string _server_ip;
   int _server_port;
};



int main(int argc,char* argv[])
{
  string server_ip=argv[1];
  int server_port = atoi(argv[2]);
  Tcp_Client* clt=new Tcp_Client(server_ip,server_port);
  clt->InitClient();
  clt->Start();
  return 0;
}

